﻿using System;
using System.Collections.Generic;
using System.Text;
using hedefgrup.reports.renault.database;
using System.Data;

namespace hedefgrup.reports.common
{
    public class Report_Verbatim : Report_Abstract
    {
        private static readonly List<string> shareMyResultsDependentQuestions = new List<string>(new string[] { "ADSOYAD", "SASENO" });

        protected override void SetCriteriaList()
        {
            Criterias.Add(new Criteria_BeginMonth() { Context = Context });
            Criterias.Add(new Criteria_EndMonth() { Context = Context });
            Criterias.Add(new Criteria_Network() { Context = Context });
            Criterias.Add(new Criteria_Organization() { Context = Context });
        }

        protected virtual string GetSelectFields()
        {
            return
                "SELECT IID, YIL, AY, DONEM = CONVERT(VARCHAR, YIL) + SUBSTRING('0' + CONVERT(VARCHAR, AY), LEN('0' + CONVERT(VARCHAR, AY) - 2), 2), " + base.DealerColumn + ", MARKA, MODELGRUP, MODEL, " +
                (
                    Context.CompatibleProjectName == Global.PROJECT_QVN2013 ?
                    "SATICI, KOORDINATOR, " + AreaColumn + ", ADSOYAD, SASENO, S18, S17, S17a, S17_OUV1, S18_OUV1, S18_OUV2, S18_MEMN, QPSC3, S19 "
                    :
                    "SATICI, KOORDINATOR, " + AreaColumn + ", ADSOYAD, SASENO, S2, S3a, S3c, S11, S4_1, S4, S4_1_S41_1 = CASE WHEN S4 = 1 OR S4_1 = 1 THEN 1 ELSE 2 END, S6, S7, S7A, S8, S8a, S8b, S9 "
                );
        }

        protected virtual List<string> GetVerbatimQuestions()
        {
            return
                Context.CompatibleProjectName == Global.PROJECT_SATIS_SUREC
                ?
                    new List<string>(new string[] { "S3a", "S3c", "S9", "S8a" })
                :
                    new List<string>(new string[] { "S18_OUV2", "S18_OUV1", "S17_OUV1", "S18_MEMN" });
        }


        protected virtual List<string> GetVerbatimOnlyQuestions()
        {
            return new List<string>();
        }

        public override ReportResult GenerateReport()
        {
            ReportResult results = new ReportResult(this);

            DataTable reportData = db.query
            (
                GetSelectFields() +
                "FROM " + Context.TableName + " " +
                GetSqlStatementFilter() +
                " ORDER BY IID ASC",
                base.GetSqlStatementParameters()
            );

            Filter_DataColumn projectNameFilter = new Filter_DataColumn("Project", typeof(string));
            projectNameFilter.Values = new List<string>();
            projectNameFilter.Values.Add(Context.CompatibleProjectName.ToUpperInvariant());

            List<Criteria> verbatimCriterias = new List<Criteria>(base.Criterias.ToArray());
            verbatimCriterias.Remove(base.GetCriteriaByName("Network"));
            verbatimCriterias.Remove(base.GetCriteriaByName("Organization"));

            DataTable verbatimData = db.query
            (
                "SELECT * FROM renault_verbatim " +
                GetSqlStatementFilter(verbatimCriterias.ToArray(), new Filter[] { projectNameFilter }) +
                " ORDER BY IID ASC",
                base.GetSqlStatementParameters(verbatimCriterias.ToArray(), new Filter[] { projectNameFilter })
            );

            Tree questionnaire = Context.Questionnaire;

            Row headerRow = new Row();
            results.HeaderRows.Add(headerRow);

            List<string> verbatimQuestions = GetVerbatimQuestions();
            List<string> verbatimOnlyQuestions = GetVerbatimOnlyQuestions();

            foreach (DataColumn dataColumn in reportData.Columns)
            {
                Tree question = questionnaire.GetChild(dataColumn.ColumnName);
                if (dataColumn.ColumnName == base.DealerColumn)
                {
                    headerRow.Cells.Add(new Cell() { Text = "BAYII KODU" });
                    headerRow.Cells.Add(new Cell() { Text = "BAYII ADI" });
                }
                else
                {
                    string cellHeader = question != null ? dataColumn.ColumnName + " - " + question["Text"] : dataColumn.ColumnName;
                    if (verbatimQuestions.Contains(dataColumn.ColumnName) && !verbatimOnlyQuestions.Contains(dataColumn.ColumnName))
                    {
                        headerRow.Cells.Add(new Cell() { Text = cellHeader + "(KOD)" });
                    }
                    headerRow.Cells.Add(new Cell() { Text = cellHeader });
                }
            }

            foreach (DataRow reportRow in reportData.Rows)
            {
                bool shareMyResults =
                    Context.CompatibleProjectName == Global.PROJECT_QVN2013 ? Convert.ToString(reportRow["S19"]) == "1" :
                    Context.CompatibleProjectName == Global.PROJECT_SSRD ? Convert.ToString(reportRow["S8"]) == "1" :
                    true;

                Row recordRow = new Row();
                results.Rows.Add(recordRow);
                foreach (DataColumn dataColumn in reportData.Columns)
                {
                    Tree question = questionnaire.GetChild(dataColumn.ColumnName);
                    string finalValue = reportRow[dataColumn].ToString();

                    if (verbatimQuestions.Contains(dataColumn.ColumnName))
                    {
                        DataRow[] verbatimRows = verbatimData.Select("YIL = " + reportRow["YIL"] + " AND AY = " + reportRow["AY"] + " AND IID = '" + reportRow["IID"] + "' AND Question = '" + dataColumn.ColumnName + "'");
                        if (verbatimRows.Length > 0)
                        {
                            finalValue = verbatimRows[0]["Content"].ToString().Replace("\r\n", " ").Replace("\n", " ").Replace("\r", " ");
                        }
                        if (!verbatimOnlyQuestions.Contains(dataColumn.ColumnName))
                        {
                            recordRow.Cells.Add(new Cell() { Text = reportRow[dataColumn].ToString().Replace(",", " ") });
                        }
                    }
                    else if (dataColumn.ColumnName == base.DealerColumn)
                    {
                        recordRow.Cells.Add(new DealerCodeCell() { Text = finalValue.Trim() });
                        finalValue = base.GetDealerName(finalValue.Trim());
                    }
                    else
                    {
                        if (question != null)
                        {
                            string[] options = finalValue.Split(',');
                            StringBuilder finalValueBuilder = new StringBuilder();

                            foreach (string option in options)
                            {
                                string optionTrimmed = option.Trim();
                                Tree optionTreeItem = question.GetChild(optionTrimmed);
                                finalValueBuilder.AppendFormat("{0}, ", optionTreeItem != null ? optionTrimmed + "-" + optionTreeItem["Text"] : optionTrimmed);
                            }

                            finalValueBuilder.Length -= 2;
                            finalValue = finalValueBuilder.ToString();
                        }
                    }

                    if (shareMyResultsDependentQuestions.Contains(dataColumn.ColumnName) && !shareMyResults)
                    {
                        finalValue = "**********";
                    }

                    recordRow.Cells.Add(new Cell() { Text = finalValue });
                }
            }

            return results;
        }

        public override string DisplayName
        {
            get { return "Yorumlar"; }
        }

        public override bool SupportsProject(string projectName)
        {
            return base.SupportsProject(projectName) || projectName == Global.PROJECT_SATIS_SUREC;
        }

        public override string SortPrefix
        {
            get { return "0x02"; }
        }
    }
}
